﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using RosService;
using RosService.Files;

namespace ABC.Business.Web.Handlers
{
    public class ImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var query = DecodingQueryParam(context.Request.QueryString["q"]);
            var imageType = (ImageType)Enum.Parse(typeof(ImageType), query["imagetype"]);
            int idNode, width, height;
            int.TryParse(query["id_node"], out idNode);
            int.TryParse(query["width"], out width);
            int.TryParse(query["height"], out height);
            byte[] file = null;

            using (var client = new Client())
            {
                switch (imageType)
                {
                    case ImageType.Full:
                        {
                            file = client.Файлы.ПолучитьФайлПолностью(idNode, Хранилище.Оперативное, client.Домен);
                        }
                        break;
                    case ImageType.Thumbnail:
                        {
                            file = client.Файлы.ПолучитьФайлПросмотр(idNode, ImageType.Thumbnail, width, width, ImageFormat.Jpg, 90);
                        }
                        break;
                    case ImageType.Resize:
                        {
                            file = client.Файлы.ПолучитьФайлПросмотр(idNode, ImageType.Resize, width, height, ImageFormat.Jpg, 90);
                        }
                        break;
                }
            }

            context.Response.ContentType = "image/jpeg";
            context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(10));
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetMaxAge(TimeSpan.FromMinutes(10));
            context.Response.Cache.SetValidUntilExpires(false);
            if (file != null) context.Response.OutputStream.Write(file, 0, file.Length);
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private NameValueCollection DecodingQueryParam(string query)
        {
            query = Encoding.UTF8.GetString(Convert.FromBase64String(query));
            return HttpUtility.ParseQueryString(query);
        }
    }
}